package com.zhou.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhou.configure.PushConfigure;
import com.zhou.dto.*;
import com.zhou.service.OtherInterfaceService;
import com.zhou.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author lcz
 * @desc 其他接口服务impl
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Service
@Slf4j
public class OtherInterfaceServiceImpl implements OtherInterfaceService {
    @Resource
    private WeatherService weatherService;
    @Autowired
    private PushConfigure pushConfigure;

    /**
     * 彩虹屁接口调用
     *
     * @return {@link Result}
     */
    @Override
    public Result getRainbow() {
        String httpUrl = "http://api.tianapi.com/caihongpi/index?key=" + pushConfigure.getRainbowKey();
        BufferedReader reader = null;
        String rs = null;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                stringBuilder.append(strRead);
                stringBuilder.append("\r\n");
            }
            reader.close();
            rs = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(rs);

        Result result = new Result();
        if (jsonObject == null) {
            //接口地址有误或者接口没调通
            result.setCode("500");
            result.setMessage("天行数据接口不通,请检查接口地址!");
            return result;
        }
//            获取接口响应状态
        String code = jsonObject.getString("code");
        if (!"200".equals(code)) {
//            如果响应状态不为200,则调用出错
            String msg = jsonObject.getString("msg");
            result.setCode(code);
            result.setMessage("天行数据接口调用报错:" + msg);
            return result;
        }
        JSONArray newslist = jsonObject.getJSONArray("newslist");
        String data = "\n" + newslist.getJSONObject(0).getString("content");
        result.setCode(code);
        result.setData(data);
        return result;
    }

    /**
     * 根据经纬度获取天气数据
     *

     * @return {@link Map}<{@link String}, {@link String}>
     */
    @Override
    @NotNull
    public Map<String, String> getWeatherMap(IdentityInfo identityInfo) {
        Map<String, String> personalInformationMap = new HashMap<>();

        // 获取天气数据,先判断是否使用丫丫天气接口
        //丫丫天气接口
        Map<String, String> mapYaYa = new HashMap<>();
        mapYaYa.put("city", identityInfo.getLatitude() + "," + identityInfo.getLongitude());
        mapYaYa.put("key", pushConfigure.getYy_weather_ak());
        WeatherYaYa weatherYaYa = (WeatherYaYa) weatherService.getYaYaWeather(mapYaYa).getData();
        if (ObjectUtils.isNotEmpty(weatherYaYa)) {
            personalInformationMap.put("location", identityInfo.getAddress());
            personalInformationMap.put("now_temp", weatherYaYa.getQw());
            personalInformationMap.put("now_weather", weatherYaYa.getTq());
            personalInformationMap.put("now_wind_dir", weatherYaYa.getFx());
            personalInformationMap.put("now_wind_class", weatherYaYa.getFl());
            personalInformationMap.put("now_rh", weatherYaYa.getSd());
            personalInformationMap.put("today_weather", weatherYaYa.getTq1() + weatherYaYa.getTq2());
            personalInformationMap.put("today_high", weatherYaYa.getNumtq1());
            personalInformationMap.put("today_low", weatherYaYa.getNumtq2());
        } else {
            //百度天气接口
            Map<String, String> mapBaiDu = new HashMap<>();
            mapBaiDu.put("district_id", identityInfo.getDistrictId());
            mapBaiDu.put("ak", pushConfigure.getBaidu_ak());
            Weather weather = (Weather) weatherService.getBaiDuWeather(mapBaiDu).getData();
            personalInformationMap.put("location", weather.getCityName());
            personalInformationMap.put("now_temp", weather.getTemp());
            personalInformationMap.put("now_weather", weather.getText_now());
            personalInformationMap.put("now_wind_dir", weather.getWd_day());
            personalInformationMap.put("now_wind_class", weather.getWc_day());
            personalInformationMap.put("now_rh", weather.getRh());
            personalInformationMap.put("today_weather", weather.getText_day() + weather.getText_night());
            personalInformationMap.put("today_high", weather.getHigh());
            personalInformationMap.put("today_low", weather.getLow());
        }

        Result rainbowResult = getRainbow();
        if ("200".equals(rainbowResult.getCode())) {
            String poem = (String) rainbowResult.getData();
            poem = poem.replaceAll("\r|\n", "");
            personalInformationMap.put("poem", poem);
        } else {
            personalInformationMap.put("poem", "今天没有诗词哦~");
        }
        return personalInformationMap;
    }

    /**
     * 获取全网热点事件
     *
     * @param colaKey 可乐钥匙
     * @return {@link Result}
     */
    @Override
    public Result getHotSpot(String colaKey) {
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject("https://luckycola.com.cn/tools/newsHot?ColaKey={colaKey}", String.class, colaKey);
        JSONObject json = JSONObject.parseObject(res);

        Result result = new Result();
        if (json == null) {
            //接口地址有误或者接口没调通
            result.setCode("500");
            result.setMessage("接口不通,请检查接口地址!");
            return result;
        }
//            获取接口响应状态
        if (!"0".equals(json.getString("code"))) {
//            响应状态不为0即调用出错
            String err = json.getString("msg");
            result.setCode("500");
            result.setMessage("天气接口调用报错:" + err);
            return result;
        }
        JSONArray items = json.getJSONObject("data").getJSONArray("items");
        List<HotSpot> hotSpot = items.toJavaList(HotSpot.class);
        result.setCode("200");
        result.setData(hotSpot);
        return result;
    }


}
